package util;

import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import server.FileServer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;

/**
 * User: tum0r
 * Package Name: util
 * Time: 2019-04-14 Sunday 15:27:36
 */
public class UploadFile {
    public String[] getUploadFile(ServletConfig servletConfig, HttpServletRequest request, HttpServletResponse response, String type) {
        String[] result = null;
        SmartUpload smartUpload = new SmartUpload();
        try {
            smartUpload.initialize(servletConfig, request, response);
            smartUpload.setAllowedFilesList(type);
            long size = 1024 * 1024 * 20;
            smartUpload.setMaxFileSize(size);
            smartUpload.setTotalMaxFileSize(size);
            smartUpload.setDeniedFilesList("exe,bat,jsp,htm,html,php,asp,php5,php3");
            smartUpload.upload();
        } catch (SmartUploadException | SQLException | ServletException | IOException e) {
            e.printStackTrace();
        }
        Files files = smartUpload.getFiles();

        int count = files.getCount();

        String path = UUID.randomUUID().toString().replace("-", "") + File.separator;
        File savePath = new File(path);
        savePath.mkdir();

        com.jspsmart.upload.File file;
        try {
            for (int i = 0; i < count; i++) {
                file = files.getFile(i);
                file.saveAs(path + file.getFileName());
            }
        } catch (IOException | SmartUploadException e) {
            e.printStackTrace();
        }

        FileServer fileServer = new FileServer();
        fileServer.open();
        File[] saveFiles = savePath.listFiles();
        result = new String[count];
        if (saveFiles != null) {
            for (int i = 0; i < saveFiles.length; i++) {
                result[i] = fileServer.saveFile(saveFiles[i]);
                saveFiles[i].delete();
            }
        }
        fileServer.close();

        savePath.delete();

        return result;
    }
}
